package com.example.springboot.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Sell;
import com.example.springboot.service.SellService;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

@CrossOrigin
@RestController

@RequestMapping("/sell")
public class SellController {
    @Autowired
    SellService sellService;
    
    @PostMapping("/add")
    public Result add(@RequestBody Sell sell){
        try{
            sellService.save(sell);
        }catch(Exception e){
            return Result.error("插入数据错误");
        }
        return Result.success();
    }
    
    @PutMapping("/update")
    public Result update(@RequestBody Sell sell){
        try{
            sellService.updateById(sell);
        }catch(Exception e){
            return Result.error("更新数据错误");
        }
        return Result.success();
    }
    
    @DeleteMapping("/delete/{orderid}")
    public Result delete(@PathVariable Integer orderid){
        try{
            sellService.removeById(orderid);
        }catch(Exception e){
            return Result.error("删除数据错误");
        }
        return Result.success();
    }
    
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Sell> sellList=sellService.list();
        return Result.success(sellList);
    }
    
    @GetMapping("/selectByOrderId/{orderid}")
    public Result selectByOrderId(@PathVariable Integer orderid){
        Sell sell=sellService.getById(orderid);
        return Result.success(sell);
    }
    @GetMapping("/selectByTime/{time}")
    public Result selectByTime(@PathVariable String time){
        QueryWrapper<Sell> queryWrapper = new QueryWrapper<>();
        // 使用 leftLike 方法来匹配年月开头的部分
        queryWrapper.like("time", time);
        List<Sell> list4= sellService.list(queryWrapper);
        return Result.success(list4);
    }
    @GetMapping("/export")
        public void exportData(@RequestParam(required = false) String time,
                           @RequestParam(required = false) String isbn,
                           @RequestParam(required = false) String orderids,
                           HttpServletResponse response) throws IOException{
        ExcelWriter writer =ExcelUtil.getWriter(true);
        List<Sell> list;
        QueryWrapper<Sell> queryWrapper = new QueryWrapper<Sell>();
        if(StrUtil.isNotBlank(orderids)){
            List<String> orderidsArr=Arrays.stream(orderids.split(",")).collect(Collectors.toList());
            queryWrapper.in("orderid",orderidsArr);
        }else{
            //第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(time), "time", time);
            queryWrapper.like(StrUtil.isNotBlank(isbn), "isbn", isbn);

        }
        list=sellService.list(queryWrapper);
        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("售书信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam String time,
                            @RequestParam String isbn) {
        QueryWrapper<Sell> queryWrapper = new QueryWrapper<Sell>();
        queryWrapper.like(StrUtil.isNotBlank(time), "time", time);
        queryWrapper.like(StrUtil.isNotBlank(isbn), "isbn", isbn);
        // select * from user where count like '%#{count}%' and name like '%#{name}%'
        Page<Sell> page = sellService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
}
